import { ref, defineComponent, onMounted, unref, watch } from 'vue'
import './style/style.less'
import { AreaTypeValue } from '@/views/test/advanced/tsx/area/area'
import { SelectParams } from '@/components/base/form-item/props/form-item-params'
import { BasePage } from '@/entity/base-model'

/**
 * 更新级联参数
 */
export interface UpdateSelect {
  value: string
  order: number
  option: any
}
/**
 * 区域选择
 */
const AreaSelect = defineComponent({
  props: {
    // 请求方法
    action: {
      required: true,
      type: Function,
    },
    // 表单项配置参数
    params: {
      type: Object,
      default: () => {},
    },
    // 数据值（v-model）
    value: {
      required: true,
      type: String,
      default: '',
    },
    // 当前选择框顺序
    order: {
      type: Number,
      required: true,
      default: 0,
    },
    // 区域参数
    typeValue: {
      required: true,
      type: Object,
      default: () => {},
    },
  },
  // 最终返回的数据,数组
  emits: ['update:value', 'globalUpdate'],
  setup(_props, { slots, emit, expose }) {
    const style = {
      width: '120px',
    }
    const { order, action, params, value, typeValue } = _props
    const config = unref(params) as SelectParams
    const options = ref([])
    let val = ref('')
    onMounted(() => {
      // 初始情况下，只有第一个会请求
      if (order == 0) {
        let param = (typeValue as AreaTypeValue)?.firstParams
        updateData(param)
      }
      val.value = value
    })

    /**
     * 更新当前选项的方法
     * @param params 参数
     */
    const updateData = async (params: BasePage = {}) => {
      params.pageNum = 0
      params.pageSize = 0
      const { data } = await action(params)
      options.value = data
    }
    function handlerChange(value: string, option: unknown) {
      val.value = value
      // 局部更新
      emit('update:value', value)
      // 全局更新
      emit('globalUpdate', { value, order, option })
    }
    // todo 暴露更新数据的方法给父组件
    expose({ updateData, val })
    return () => (
      <a-select
        onSelect={handlerChange}
        notFoundContent={config?.notFoundContent}
        showSearch={config?.showSearch}
        fieldNames={config?.fieldNames}
        allowClear={config?.allowClear}
        autoClearSearchValue={config?.autoClearSearchValue}
        autofocus={config?.autofocus}
        bordered={config?.bordered}
        defaultOpen={config?.defaultOpen}
        defaultActiveFirstOption={config?.defaultActiveFirstOption}
        disabled={config?.disabled}
        placeholder={config?.placeholder}
        style={style}
        value={val}
        options={options}
      />
    )
  },
})

export default AreaSelect
